import { useUserStore } from '@/store';

let isRefreshing = false; // 标记是否正在刷新 token
let requests = []; // 存储待重发请求的数组

export async function handleTokenExpire(http, res) {
  const { config } = res;

  if (isRefreshing === true) {
    return new Promise((resolve) => requests.push(() => resolve(http(config))));
  }

  isRefreshing = true;
  // 令牌刷新
  const { refreshToken } = useUserStore();
  await refreshToken().finally(() => {
    isRefreshing = false;
  });

  requests.forEach((request) => request());
  requests = [];

  return http(config);
}
